﻿namespace WebPacker.VersionGenerators
{
	using System;
	using System.Collections;
	using System.Collections.Generic;

	public sealed class VersionGeneratorCollection : ICollection<IVersionGenerator>
	{
		private readonly IList<IVersionGenerator> items;

		public VersionGeneratorCollection()
		{
			items = new List<IVersionGenerator>();
		}

		public int Count
		{
			get { return items.Count; }
		}

		public bool IsReadOnly
		{
			get { return false; }
		}

		public void Add(IVersionGenerator item)
		{
			if (item == null)
			{
				throw new ArgumentNullException("item");
			}

			if (item.Name == null)
			{
				throw new ArgumentNullException("item.Name");
			}

			if (Contains(item.Name))
			{
				throw new ArgumentException(string.Format("Version generator \"{0}\" is registered allready.", item.Name));
			}

			items.Add(item);
		}

		public void AddRange(IEnumerable<IVersionGenerator> items)
		{
			if (items == null)
			{
				throw new ArgumentNullException("items");
			}

			foreach (var item in items)
			{
				Add(item);
			}
		}

		public void Clear()
		{
			items.Clear();
		}

		public bool Contains(IVersionGenerator item)
		{
			return items.Contains(item);
		}

		public bool Contains(string name)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}

			return IndexOf(name) != -1;
		}

		public void CopyTo(IVersionGenerator[] array, int arrayIndex)
		{
			items.CopyTo(array, arrayIndex);
		}

		public IVersionGenerator GetItem(string name)
		{
			IVersionGenerator versionGenerator = null;

			if (!TryGetItem(name, out versionGenerator))
			{
				throw new ArgumentException(string.Format("Version generator \"{0}\" isn't found.", name));
			}

			return versionGenerator;
		}

		public bool TryGetItem(string name, out IVersionGenerator versionGenerator)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}

			var index = IndexOf(name);
			versionGenerator = index != -1 ? items[index] : null;
			return versionGenerator != null;
		}

		public bool Remove(IVersionGenerator item)
		{
			return items.Remove(item);
		}

		public bool Remove(string name)
		{
			if (name == null)
			{
				throw new ArgumentNullException("name");
			}

			var index = IndexOf(name);

			if (index != -1)
			{
				items.RemoveAt(index);
			}

			return index != -1;
		}

		public IEnumerator<IVersionGenerator> GetEnumerator()
		{
			return items.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return items.GetEnumerator();
		}

		private int IndexOf(string name)
		{
			var index = -1;

			for (var i = 0; i < items.Count; i++)
			{
				var item = items[i];

				if (item.Name == name)
				{
					index = i;
					break;
				}
			}

			return index;
		}
	}
}
